<?php


namespace app\index\controller;
use app\common\controller\Base;
use think\Db;
use think\facade\Request;
use app\common\model\User as UserModel;
use think\facade\Session;


class User extends Base
{
    //注册页面
    public function register(){
        //判断是否可以注册
        $this->isReg();
        $this->assign('title','用户注册');
        return $this->fetch();
    }
    //处理用户提交的用户信息
    public function insert(){
        if(Request::isAjax()){
            //验证数据
            $data=Request::post(); //要验证的数据
            $rule='app\common\validate\User';  //自定义的验证规则
            //开始验证
            $res=$this->validate($data,$rule);
            if($res!==true){
                //验证失败
                return ['status'=>-1,'msg'=>$res];
            }else{
                //获取用户通过表单提交过来的数据
                $data=Request::except('password_confirm','post');
                if(UserModel::create($data)){
                    return ['status'=>1,'msg'=>'注册成功'];
                }
            }
        }else{
                return ['status'=>0,'msg'=>'注册失败'];
        }
    }


    //用户登录
    public function login(){
        $this->logined();     //防止重复登录
        return $this->fetch('login',['title','用户登录']);
    }

    //登录验证
    public function loginCheck(){
        if(Request::isAjax()){
            //验证数据
            $data=Request::post(); //要验证的数据
            $rule=[
                'name|用户名'=>'require',
                'password|密码'=>'require|alphaNum'
            ];  //自定义的验证规则
            //开始验证
            $res=$this->validate($data,$rule);
            if($res!==true){
                //验证失败
                return ['status'=>-1,'msg'=>$res];
            }else{
                //获取用户通过表单提交过来的数据
                $data=Request::post();
                $result=Db::table('zh_user')->where([
                    'name'=>$data['name'],
                    'password'=>sha1($data['password'])
                ])->find();
                if($result!=null){
                    //将用户的数据写到session
                    Session::set('user_id',$result['id']);
                    Session::set('user_name',$result['name']);
                    return ['status'=>1,'msg'=>'登录成功'];
                }else{
                    return ['status'=>0,'msg'=>'用户名或密码错误'];
                }
            }
        }
    }

    //退出登录
    public function logout(){
        Session::delete('user_id');
        Session::delete('user_name');
        $this->success('退出登录成功','index/index');
    }



}